home *** CD-ROM | disk | FTP | other *** search
/ C/C++ Users Group Library 1996 July / C-C++ Users Group Library July 1996.iso / listings / v_12_06 / allison / hi_lo2.c < prev    next >
C/C++ Source or Header  |  1994-04-08  |  1KB  |  59 lines

  1. LISTING 8 - Removes extraneous loop controls from Listing 2
  2.  
  3. /* hi-lo2.c:    Removes extraneous boolean flags */
  4.  
  5. #include <stdio.h>
  6. #include <ctype.h>
  7.  
  8. main()
  9. {
  10.     puts("Think of a number between 1 and 100.");
  11.     puts("If you don't cheat, I'll figure it out");
  12.     puts("in seven guesses or less!\n");
  13.  
  14.     for (;;)    /* An idiom for REPEAT FOREVER */
  15.     {
  16.         int lo = 1, hi = 100;
  17.         int guess;
  18.         char response;
  19.  
  20.         /* Play the Game */
  21.         while (lo <= hi)
  22.         {
  23.             /* Get response */
  24.             guess = (lo + hi) / 2;
  25.             printf("Is it %d (L/H/Y): ",guess);
  26.             fflush(stdout);
  27.             scanf("%c%*c",&response);
  28.             response = toupper(response);
  29.  
  30.             /* Narrow the search range */
  31.             if (response == 'L')
  32.                 lo = guess + 1;
  33.             else if (response == 'H')
  34.                 hi = guess - 1;
  35.             else if (response != 'Y')
  36.                 puts("What? Try again...");
  37.             else
  38.                 break;
  39.         }
  40.  
  41.         /* Print results */
  42.         if (lo > hi)
  43.             puts("You cheated!");
  44.         else
  45.         {
  46.             printf("Your number was %d\n",guess);
  47.             puts("What fun!");
  48.         }
  49.  
  50.         printf("Wanna play again? ");
  51.         fflush(stdout);
  52.         scanf("%c%*c",&response);
  53.         if (toupper(response) != 'Y')
  54.             break;
  55.     }
  56.     return 0;
  57. }
  58.  
  59.